from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ModelViewSet

from apps.goods.models import SKU, GoodsCategory, SPU, SPUSpecification
from apps.meiduo_mall_admin.serializers.sku import SKUSerializer, SKUCategorieSerializer, GoodsSimpleSerializer, \
    GoodsSpecSerialzier
from apps.meiduo_mall_admin.utils import PageNum


class SKUModelViewSet(ModelViewSet):
    """获取SKU表数据"""

    # SKU序列化器
    serializer_class = SKUSerializer
    # 分页
    pagination_class = PageNum

    # 重写方法获取SKU表数据
    def get_queryset(self):
        # 提取keyword
        keyword = self.request.query_params.get("keyword")

        # keyword进行校验
        if keyword == "" or keyword is None:
            return SKU.objects.all()
        else:
            return SKU.objects.filter(name=keyword)


class SKUCategoriesView(ListAPIView):
    """获取三级分类信息"""

    # 三级分类序列化器
    serializer_class = SKUCategorieSerializer
    # 根据数据存储规律parent_id大于37为三级分类信息，查询条件为parent_id__gt=37
    queryset = GoodsCategory.objects.filter(parent_id__gt=37)


class GoodsSimpleView(ListAPIView):
    """获取SPU表名称信息"""

    # 定义序列化器
    serializer_class = GoodsSimpleSerializer

    # 获取表数据信息
    queryset = SPU.objects.all()


class GoodsSpecView(ListAPIView):
    """获取SPU商品规格信息"""

    # 设置序列化器
    serializer_class = GoodsSpecSerialzier
    # 因为继承的是ListAPIView，在拓展类中是通过get_queryset获取数据，但是我们现在要获取的是规格信息，所以重写get_queryset
    def get_queryset(self):
        pk = self.kwargs["pk"]
        return SPUSpecification.objects.filter(spu_id=pk)


class SKUGoodsView(ModelViewSet):
    """保存SKU数据"""

    # 定义序列化器
    serializer_class = SKUSerializer

    # 分页
    pagination_class = PageNum

    # 通过get_queryset获取keyword
    def get_queryset(self):
        # 提取keyword
        keyword = self.request.query_params.get("keyword")
        # 进行判断
        if keyword == "" or keyword is None:
            # 如果为空，则返回SKU模型类的所有数据
            return SKU.objects.all()
        else:
            # 如果不为空则筛选出来keyword
            return SKU.objects.filter(name=keyword)